import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Borrower from '../views/Borrower.vue'
import Book from '../views/Book.vue'
import Borrow from '../views/Borrow.vue'
import Fine from '../views/Fine.vue'

const routes = [
  { path: '/login', component: Login },
  { path: '/borrower', component: Borrower },
  { path: '/book', component: Book },
  { path: '/borrow', component: Borrow },
  { path: '/fine', component: Fine },
  { path: '/', redirect: '/login' }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫：刷新网页时自动退出登录
let firstLoad = true
router.beforeEach((to, from, next) => {
  if (firstLoad) {
    localStorage.removeItem('token')
    firstLoad = false
    if (to.path !== '/login') {
      next('/login')
      return
    }
  }
  const token = localStorage.getItem('token')
  if (to.path !== '/login' && (!token || token === 'null' || token === 'undefined')) {
    next('/login')
  } else {
    next()
  }
})

export default router 